<template>
  <div class="hello">
    <!--开启摄像头的弹窗-->
    <!-- <div class="info2" @click="onTake">
      <el-image :src="url" style="width: 100%; height: 100%"></el-image>
    </div> -->
    <!--开启摄像头的拍照和-->
    <el-dialog :modal-append-to-body="false" :append-to-body="true" title="拍照上传" :visible.sync="cameraVisible" @close="onCancel1" width="1065px">
      <div class="box">
        <video id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight" autoPlay></video>
        <canvas id="canvasCamera" class="canvas" :width="videoWidth" :height="videoHeight"></canvas>
      </div>
      <div slot="footer">
        <el-button @click="drawImage" icon="el-icon-camera" size="small">
          拍照
        </el-button>
        <el-button v-if="os" @click="getCompetence" icon="el-icon-video-camera" size="small">
          打开摄像头
        </el-button>
        <el-button v-else @click="stopNavigator" icon="el-icon-switch-button" size="small">
          关闭摄像头
        </el-button>
        <el-button @click="resetCanvas" icon="el-icon-refresh" size="small">
          重置
        </el-button>
        <el-button @click="onCancel" icon="el-icon-circle-close" size="small">
          完成
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    upload as uploadImage,getImg as getLoadImage
  } from '@/api/file'
  export default {
    name: "Camera",
    props: {
		avatar:{
			type: String,
			default:'http://192.168.1.22:8091/chronicle/5811cd1077494cfe9b991b9dc9cccb2f.png'
		}

    },
    data() {
      return {
        url: "http://192.168.1.22:8091/chronicle/5811cd1077494cfe9b991b9dc9cccb2f.png", // 上传的图片的地址
        cameraVisible: false, //弹窗
        videoWidth: 500, // 绘画布的宽高
        videoHeight: 400,
        os: false, //控制摄像头开关
        thisCancas: null,
        thisContext: null,
        thisVideo: null,
        imgSrc: undefined,
        imgFile: null,
		imageApi: process.env.VUE_APP_IMAGE_BASE_URL,
      };
    },
    mounted() {
      this.searchDevice();
    },
    methods: {
	  init(){
		  this.cameraVisible = true
		  this.onTake()
	  },
      searchDevice() {
        if (window.navigator.mediaDevices && window.navigator.mediaDevices.getUserMedia) {}
        navigator.mediaDevices.enumerateDevices().then((devices) => {
          let videoList = devices.filter((item) => {
            return item.kind == "videoinput";
          });
          this.devicesList = videoList;
          if (videoList.length == 0) {
            // this.$message({
            //   message: "没有查询到视频输入设备！",
            //   type: "error",
            // });
            return false;
          } else if (videoList.length == 1) {
            this.currentDeviceID = videoList[0].deviceId;
          } else if (videoList.length > 1) {
            this.$message({
              message: "当前设备有多个视频输入设备，可根据需要切换视频输入设备",
              type: "info",
            });
          }
        });
      },
      /*调用摄像头拍照开始*/
      onTake() {
        this.cameraVisible = true;
        this.getCompetence();
      },

      /*关闭弹窗，以及关闭摄像头功能*/
      onCancel1() {
        this.cameraVisible = false;
        this.stopNavigator(); // 关闭摄像头
      },

      // 调用摄像头权限
      getCompetence() {
        //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
        this.$nextTick(() => {
          const _this = this;
          this.os = false; //切换成关闭摄像头
          // 获取画布节点
          this.thisCancas = document.getElementById("canvasCamera");
          // 为画布指定绘画为2d类型
          this.thisContext = this.thisCancas.getContext("2d");
          //获取video节点
          this.thisVideo = document.getElementById("videoCamera");
          // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
          if (navigator.mediaDevices === undefined) {
            navigator.menavigatordiaDevices = {};
          }
          // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
          // 使用getUserMedia，因为它会覆盖现有的属性。
          // 这里，如果缺少getUserMedia属性，就添加它。
          // if (navigator.mediaDevices.getUserMedia === undefined) {
          //   navigator.mediaDevices.getUserMedia = function(constraints) {
          //     // 首先获取现存的getUserMedia(如果存在)
          //     let getUserMedia =
          //       navigator.webkitGetUserMedia ||
          //       navigator.mozGetUserMedia ||
          //       navigator.getUserMedia;
          //     // 有些浏览器不支持，会返回错误信息
          //     // 保持接口一致
          //     if (!getUserMedia) {
          //       return Promise.reject(
          //         new Error("getUserMedia is not implemented in this browser")
          //       );
          //     }
          //     // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          //     return new Promise(function(resolve, reject) {
          //       getUserMedia.call(navigator, constraints, resolve, reject);
          //     });
          //   };
          // }
          const constraints = {
            audio: false,
            video: {
              width: _this.videoWidth,
              height: _this.videoHeight,
              transform: "scaleX(-1)"
            }
          };
          navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
              // 旧的浏览器可能没有srcObject
              if ("srcObject" in _this.thisVideo) {
                _this.thisVideo.srcObject = stream;
              } else {
                // 避免在新的浏览器中使用它，因为它正在被弃用。
                _this.thisVideo.src = window.URL.createObjectURL(stream);
              }
              _this.thisVideo.onloadedmetadata = function(e) {
                console.log(e)
                _this.thisVideo.play();
              };
            })
            .catch(err => {
              console.log(err)
              this.$notify({
                title: "警告",
                message: "没有开启摄像头权限或浏览器版本不兼容.",
                type: "warning"
              });
            });
        });
      },

      //调用摄像头 --- 进行绘制图片
      drawImage() {
        // 点击，canvas画图
        this.thisContext.drawImage(
          this.thisVideo,
          0,
          0,
          this.videoWidth,
          this.videoHeight
        );
        // 获取图片base64链接
        this.imgSrc = this.thisCancas.toDataURL("image/png");
        /*const imgSrc=this.imgSrc;*/
      },
      //清空画布
      clearCanvas(id) {
        let c = document.getElementById(id);
        let cxt = c.getContext("2d");
        cxt.clearRect(0, 0, c.width, c.height);
      },

      //重置画布
      resetCanvas() {
        // this.imgSrc = "";
        this.clearCanvas("canvasCamera");
      },

      //关闭摄像头
      stopNavigator() {
        if (this.thisVideo && this.thisVideo !== null) {
          this.thisVideo.srcObject.getTracks()[0].stop();
          this.os = true; //切换成打开摄像头
        }
      },
      /*调用摄像头拍照结束*/

      /*完成拍照并对其照片进行上传*/
      async onCancel() {
        this.cameraVisible = false;
        /* this.resetCanvas();*/
        // console.log(this.imgSrc);
        this.imgFile = this.dataURLtoFile(this.imgSrc, new Date() + ".png");
        this.stopNavigator();
        // let par = {
        //   photo: this.imgFile,
        // };
        let data = new FormData();
        data.append("file", this.imgFile); //1是图片，2是视频
        // uploadImage上传图片的接口
		let res = await uploadImage(data)
		if (res.httpCode == "200") {
		console.log(res,'path上传')
		  this.$message({
			message: "上传成功",
			type: "success"
		  });
		}
		// let res1 = await getLoadImage(res.data.path)
		// const buffer = Buffer.from(res1)
		// let base64 = this.arrayBufferToBase64(buffer)
		// let base64Url  = "data:image/png;base64,"+base64
		// this.url = base64Url
		// this.$emit('unpdateAvatar',res.data.path,this.url)

		this.$emit('unpdateAvatar',res.data.path)
      },
	  blobToUrl(blob_data) {
	      return URL.createObjectURL(blob_data)
	  },
	  base642Url(data) {
	      var parts = data.split(';base64,'),
	          contentType = parts[0].split(':')[1],
	          raw = window.atob(parts[1]),
	          length = raw.length,
	          arr = new Uint8Array(length);
	      for (var i = 0; i < length; i++) {
	          arr[i] = raw.charCodeAt(i);
	      }
	      var blob = new Blob([arr], { type: contentType });
	      return URL.createObjectURL(blob);
	  },
	  pngBase64ToBlob(urlData) {
	      try {
	          var arr = urlData.split(',')
	          var mime = arr[0].match(/:(.*?);/)[1] || 'image/png';
	          // 去掉url的头，并转化为byte
	          var bytes = window.atob(arr[1]);
	          // 处理异常,将ascii码小于0的转换为大于0
	          var ab = new ArrayBuffer(bytes.length);
	          // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
	          var ia = new Uint8Array(ab);

	          for (var i = 0; i < bytes.length; i++) {
	              ia[i] = bytes.charCodeAt(i);
	          }

	          return new Blob([ab], {
	              type: mime
	          });
	      }
	      catch (e) {
	          var ab = new ArrayBuffer(0);
	          return new Blob([ab], {
	              type: 'image/png',
	          });
	      }
	  },
	arrayBufferToBase64 (buffer) {
	      var binary = ''
	      var bytes = new Uint8Array(buffer)
	      var len = bytes.byteLength
	      for (var i = 0; i < len; i++) {
	        binary += String.fromCharCode(bytes[i])
	      }
	      return window.btoa(binary)
	    },
      dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(",");
        var mime = arr[0].match(/:(.*?);/)[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      }
    }
  };
</script>

<style scoped>
  .info2 {
    width: 10%;
    height: 100px;
  }

  .box {
    display: flex;
  }
</style>
